"use strict";

const db = uniCloud.database();
const offlineMapCollection = db.collection("map-offline-areas");

exports.main = async (event, context) => {
  const { action, data, uniIdToken } = event;

  // 获取用户身份信息
  let userInfo;
  try {
    const uniID = require("uni-id-common");
    const idInstance = uniID.createInstance({ context });
    userInfo = await idInstance.checkToken(uniIdToken);
    if (userInfo.code !== 0) {
      return { code: 401, message: "未授权，请登录后操作" };
    }
  } catch (e) {
    return { code: 502, message: "服务器异常" };
  }

  const userId = userInfo.uid;

  switch (action) {
    // 保存离线地图区域
    case "saveOfflineArea": {
      try {
        const {
          name,
          center_latitude,
          center_longitude,
          scale,
          size = 0,
        } = data;

        // 验证必要数据
        if (!center_latitude || !center_longitude || !scale) {
          return { code: 400, message: "地图数据不完整" };
        }

        // 默认名称
        const mapName = name || `离线地图 ${new Date().toLocaleString()}`;

        // 计算范围 (简化计算，实际应考虑地球曲率)
        // 每缩放级别差距约为2倍，16级为街区级别
        const rangeInDegrees = 0.01 * Math.pow(2, 16 - scale);

        const mapData = {
          user_id: userId,
          name: mapName,
          center_latitude,
          center_longitude,
          scale,
          min_latitude: center_latitude - rangeInDegrees,
          max_latitude: center_latitude + rangeInDegrees,
          min_longitude: center_longitude - rangeInDegrees,
          max_longitude: center_longitude + rangeInDegrees,
          size,
          create_date: new Date(),
          update_date: new Date(),
        };

        const result = await offlineMapCollection.add(mapData);
        return {
          code: 0,
          message: "离线地图区域保存成功",
          data: { id: result.id },
        };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "保存离线地图区域失败" };
      }
    }

    // 获取离线地图区域列表
    case "getOfflineAreaList": {
      try {
        const { page = 1, pageSize = 10 } = data;
        const skip = (page - 1) * pageSize;

        const list = await offlineMapCollection
          .where({ user_id: userId })
          .orderBy("create_date", "desc")
          .skip(skip)
          .limit(pageSize)
          .get();

        const total = await offlineMapCollection
          .where({ user_id: userId })
          .count();

        return {
          code: 0,
          message: "获取离线地图区域列表成功",
          data: {
            list: list.data,
            pagination: {
              page,
              pageSize,
              total: total.total,
            },
          },
        };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "获取离线地图区域列表失败" };
      }
    }

    // 获取离线地图区域详情
    case "getOfflineAreaDetail": {
      try {
        const { areaId } = data;
        if (!areaId) {
          return { code: 400, message: "缺少地图区域ID" };
        }

        const result = await offlineMapCollection.doc(areaId).get();
        if (result.data.length === 0) {
          return { code: 404, message: "地图区域不存在" };
        }

        const area = result.data[0];
        // 检查权限
        if (area.user_id !== userId) {
          return { code: 403, message: "无权查看该地图区域" };
        }

        return { code: 0, message: "获取地图区域详情成功", data: area };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "获取地图区域详情失败" };
      }
    }

    // 删除离线地图区域
    case "deleteOfflineArea": {
      try {
        const { areaId } = data;
        if (!areaId) {
          return { code: 400, message: "缺少地图区域ID" };
        }

        // 检查地图区域是否属于当前用户
        const areaInfo = await offlineMapCollection.doc(areaId).get();
        if (areaInfo.data.length === 0) {
          return { code: 404, message: "地图区域不存在" };
        }

        const area = areaInfo.data[0];
        if (area.user_id !== userId) {
          return { code: 403, message: "无权删除该地图区域" };
        }

        // 如果有瓦片数据，应该同时删除瓦片数据（需要云存储支持）
        // TODO: 删除云存储中的瓦片数据

        await offlineMapCollection.doc(areaId).remove();
        return { code: 0, message: "删除地图区域成功" };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "删除地图区域失败" };
      }
    }

    default:
      return { code: 400, message: "无效的操作类型" };
  }
};
